package pt.chukaku.gtgb.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import pt.chukaku.gtgb.Book;
import android.util.Log;

public class AphroheadCom {

	String isbn = "";
	Book book = null;

	public AphroheadCom(String isbn) {
		super();
		this.isbn = isbn;
		getInfo();
	}

	public Book getBook() {

		return book;
	}

	private void getInfo() {
		String str = lerPagina("http://aphrohead.com/Search.aspx?sw=" + isbn);

		// Number of results
		int posIQt = -1, posFQt, qt;
		posIQt = str.indexOf("more_pages_text_red");
		if (posIQt == -1)
			qt = 0;
		else {
			posIQt = str.indexOf("more_pages_text_red", posIQt + 10);
			posFQt = str.indexOf("</div>", posIQt);
			qt = new Integer(str.substring(posIQt + 21, posFQt));
		}

		int posI, posF;
		for (int i = 0; i < qt; i++) {
			// Author
			posI = str.indexOf("class=\"author\"");
			posF = str.indexOf("</a>", posI);
			String author = str.substring(posI + 15, posF);

			// Title
			posI = str.indexOf("class=\"title\"");
			posF = str.indexOf("</a>", posI);
			String title = str.substring(posI + 14, posF);

			// Price
			posI = str.indexOf("price_text_red");
			posF = str.indexOf("</div>", posI);
			String price = str.substring(posI + 24, posF);

			// Cover
			posI = str.indexOf("product_picture");
			posI = str.indexOf("src=", posI);
			posF = str.indexOf("\"></a>", posI);
			String cover = "http://aphrohead.com"
					+ str.substring(posI + 5, posF);
			
			//Url
			posI = str.indexOf("title_author_box");
			posI = str.indexOf("<a href=\"/", posI);
			posF = str.indexOf("\" class", posI);
			String url = "http://aphrohead.com" + str.substring(posI + 9, posF);
			

			book = new Book(title, author, price, cover,url, "Aphrohead");
		}
	}

	private String lerPagina(String urltext) {
		URL url = null;
		try {
			url = new URL(urltext);
		} catch (MalformedURLException e) {
			log("url = new URL(urltext);");
			e.printStackTrace();
		}
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(url.openStream()));
		} catch (IOException e) {
			log("in = new BufferedReader(...);");
			e.printStackTrace();
		}
		String inputLine;
		String result = "";
		try {
			while ((inputLine = in.readLine()) != null) {
				// Process each line.
				result += inputLine;
			}
		} catch (IOException e) {
			log("inputLine = in.readLine()");
			e.printStackTrace();
		}
		try {
			in.close();
		} catch (IOException e) {
			log("in.close()");
			e.printStackTrace();
		}
		return result;
	}

	private void log(String position) {
		Log.d("GTG", "AphroheadCom: " + position);
	}
}
